﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Model;

namespace Common
{
    public class CommonRoutine
    {
        /// <summary>
        /// Get local IP
        /// </summary>
        /// <returns>Ip_List</returns>
        public static ArrayList GetLocalhostIP()
        {
            IPAddress[] ip = Dns.GetHostAddresses(Dns.GetHostName());
            int count = ip.Length;
            ArrayList list = new ArrayList();
            for (int i = 0; i < count; i++)
            {
                list.Add(ip[i]);
            }
            return list;
        }



        /// <summary>
        /// Verification IP
        /// </summary>
        /// <param name="strIn"></param>
        /// <returns></returns>
        public static bool IsValidIp(string strIn)
        {
            bool ss = Regex.IsMatch(strIn,@"[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?");
            bool bb= Regex.IsMatch(strIn, @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$");
            return ss || bb;
        }

        /// <summary>
        /// Verification phoneNumber
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <returns></returns>
        public static bool IsValidPhoneNumber(string phoneNumber)
        {
            bool ss = Regex.IsMatch(phoneNumber, @"(13|15)\\d{9}");
            return ss;
        }

        /// <summary>
        /// Handling  Exceptions
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="isAretMessage"> </param>
        public static void HandlingExceptions(Exception ex,bool isAretMessage=false)
        {
            if(isAretMessage)
            {
                MessageBox.Show(ex.Message);                
            }
            LogService.WriteLog(ex.Message);
        }

        #region Calculating the distance between two points


        private const double DEF_PI = 3.14159265359; // PI
        private const double DEF_2PI = 6.28318530712; // 2*PI
        private const double DEF_PI180 = 0.01745329252; // PI/180.0
        private const double DEF_R = 6370693.5; // radius of earth

        /// <summary>
        /// calculate the short distance between two points of latitude and longitude.
        /// </summary>
        /// <param name="lon1">first point longitude</param>
        /// <param name="lat1">first point latitude</param>
        /// <param name="lon2">second point longitude</param>
        /// <param name="lat2">second point latitude</param>
        /// <returns>double distance</returns>
        private static double GetShortDistance(double lon1, double lat1, double lon2, double lat2)
        {
            // 角度转换为弧度
            double ew1 = lon1 * DEF_PI180;
            double ns1 = lat1 * DEF_PI180;
            double ew2 = lon2 * DEF_PI180;
            double ns2 = lat2 * DEF_PI180;
            // 经度差
            double dew = ew1 - ew2;
            // 若跨东经和西经180 度，进行调整
            if (dew > DEF_PI)
                dew = DEF_2PI - dew;
            else if (dew < -DEF_PI)
                dew = DEF_2PI + dew;
            double dx = DEF_R * Math.Cos(ns1) * dew;
            double dy = DEF_R * (ns1 - ns2);
            // 勾股定理求斜边长
            double distance = Math.Sqrt(dx * dx + dy * dy);
            return distance;
        }

        /// <summary>
        /// calculate the Long distance between two points of latitude and longitude.
        /// </summary>
        /// <param name="lon1">first point longitude</param>
        /// <param name="lat1">first point latitude</param>
        /// <param name="lon2">second point longitude</param>
        /// <param name="lat2">second point latitude</param>
        /// <returns>double distance</returns>
        private static double GetLongDistance(double lon1, double lat1, double lon2, double lat2)
        {
            // 角度转换为弧度
            double ew1 = lon1 * DEF_PI180;
            double ns1 = lat1 * DEF_PI180;
            double ew2 = lon2 * DEF_PI180;
            double ns2 = lat2 * DEF_PI180;
            // 求大圆劣弧与球心所夹的角(弧度)
            double distance = Math.Sin(ns1) * Math.Sin(ns2) + Math.Cos(ns1) * Math.Cos(ns2) * Math.Cos(ew1 - ew2);
            // 调整到[-1..1]范围内，避免溢出
            if (distance > 1.0)
                distance = 1.0;
            else if (distance < -1.0)
                distance = -1.0;
            // 求大圆劣弧长度
            distance = DEF_R * Math.Acos(distance);
            return distance;
        }

        public static double GetDistanceBetweenTwoGps(double lat1, double long1, double lat2, double long2)
        {
            double a, b, R;
            R = 6378137; //地球半径
            lat1 = lat1 * Math.PI / 180.0;
            lat2 = lat2 * Math.PI / 180.0;
            a = lat1 - lat2;
            b = (long1 - long2) * Math.PI / 180.0;
            double d;
            double sa2, sb2;
            sa2 = Math.Sin(a / 2.0);
            sb2 = Math.Sin(b / 2.0);
            d = 2 * R * Math.Asin(Math.Sqrt(sa2 * sa2 + Math.Cos(lat1) * Math.Cos(lat2) * sb2 * sb2));
            return d;
        }
        #endregion

        public static string IntToBinaryString(int a)
        {
            // Convert.ToInt32()byte.Parse(serverMac[i], NumberStyles.HexNumber);
            return Convert.ToString(a, 2).PadLeft(8, '0');
        }

        public static string ReverseString(string original)
        {
            char[] c = original.ToCharArray();
            int l = original.Length;
            for (int i = 0; i < l / 2; i++)
            {
                char t = c[i];
                c[i] = c[l - i - 1];
                c[l - i - 1] = t;
            }
            return new string(c);
        }

        public static string ByteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }


        public static int IpToNumber(string strIpAddress)
        {
            return BitConverter.ToInt32(IPAddress.Parse(strIpAddress).GetAddressBytes(), 0);
        }

        public static string NumberToIp(int intIPAddress)
        {
            return new IPAddress(BitConverter.GetBytes(intIPAddress)).ToString();
        }

        /// <summary>
        /// according  a  full command  return checkbit
        /// </summary>
        /// <param name="data">A full command</param>
        /// <returns></returns>
        public static byte GetCheckBit(byte[] data)
        {
            byte checkbit = data[1];
            for (int i = 2; i < data.Length - 2; i++)
            {
                checkbit = Convert.ToByte(checkbit ^ data[i]);
            }
            return checkbit;
        }

        public static Byte[] BcdStringToBytes(string strTemp)
        {
            try
            {
                if (Convert.ToBoolean(strTemp.Length & 1))//数字的二进制码最后1位是1则为奇数
                {
                    strTemp = "0" + strTemp;//数位为奇数时前面补0
                }
                Byte[] aryTemp = new Byte[strTemp.Length / 2];
                for (int i = 0; i < (strTemp.Length / 2); i++)
                {
                    aryTemp[i] = (Byte)(((strTemp[i * 2] - '0') << 4) | (strTemp[i * 2 + 1] - '0'));
                }
                return aryTemp;//高位在前
            }
            catch
            { return null; }
        }

        /// <summary>
        /// Hexadecimal conversion BCD string
        /// </summary>
        /// <param name="aData"></param>
        /// <returns></returns>
        public static string ByteToBcdString(Byte[] aData)
        {
            try
            {
                StringBuilder sb = new StringBuilder(aData.Length * 2);
                foreach (Byte b in aData)
                {
                   sb.Append(b.ToString("X2"));
                    //sb.Append(b >> 4);
                    //sb.Append(b & 0x0f);
                }
                return sb.ToString();
            }
            catch { return null; }
        }


        public static bool DownloadFileByUrl(string httpUrl, string savePath)
        {
            try
            {
                HttpWebRequest myrq = (HttpWebRequest)WebRequest.Create(httpUrl);
                HttpWebResponse myrp = (HttpWebResponse)myrq.GetResponse();
                long totalBytes = myrp.ContentLength;

                Stream st = myrp.GetResponseStream();
                Stream so = new FileStream(savePath, FileMode.Create);
                long totalDownloadedByte = 0;
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    Application.DoEvents();
                    so.Write(by, 0, osize);
                    osize = st.Read(by, 0, (int)by.Length);
                }

                so.Close();
                st.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        //  public   Color GetRandomColor()
        //{
        //    Random randomNumFirst = new Random(Guid.NewGuid().GetHashCode());
        //    //Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
        //    // 对于C#的随机数，没什么好说的 
        //    System.Threading.Thread.Sleep(randomNumFirst.Next(10));
        //    Random randomNumSencond = new Random((int)DateTime.Now.Ticks);

        //    // 为了在白色背景上显示，尽量生成深色 
        //    int intRed = randomNumFirst.Next(254);
        //    int intGreen = randomNumSencond.Next(254);
        //    int intBlue = (intRed + intGreen > 400) ? 0 : 400 - intRed - intGreen;
        //    intBlue = (intBlue > 255) ? 255 : intBlue;

        //    return Color.FromArgb(intRed, intGreen, intBlue);
        //}


        #region 

        const double pi = 3.14159265358979324;
         
        // Krasovsky 1940
        //
        // a = 6378245.0, 1/f = 298.3
        // b = a * (1 - f)
        // ee = (a^2 - b^2) / a^2;
        const double a = 6378245.0;
        const double ee = 0.00669342162296594323;

        // World Geodetic System ==> Mars Geodetic System
        public static void TransformWGSToGCJ(double wgLat, double wgLon, out double mgLat, out double mgLon)
        {
            if (outOfChina(wgLat, wgLon))
            {
                mgLat = wgLat;
                mgLon = wgLon;
                return;
            }
            double dLat = transformLat(wgLon - 105.0, wgLat - 35.0);
            double dLon = transformLon(wgLon - 105.0, wgLat - 35.0);
            double radLat = wgLat / 180.0 * pi;
            double magic = Math.Sin(radLat);
            magic = 1 - ee * magic * magic;
            double sqrtMagic = Math.Sqrt(magic);
            dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
            dLon = (dLon * 180.0) / (a / sqrtMagic * Math.Cos(radLat) * pi);
            mgLat = wgLat + dLat;
            mgLon = wgLon + dLon;
        }

        static bool outOfChina(double lat, double lon)
        {
            if (lon < 72.004 || lon > 137.8347)
                return true;
            if (lat < 0.8293 || lat > 55.8271)
                return true;
            return false;
        }

        static double transformLat(double x, double y)
        {
            double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.Sqrt(Math.Abs(x));
            ret += (20.0 * Math.Sin(6.0 * x * pi) + 20.0 * Math.Sin(2.0 * x * pi)) * 2.0 / 3.0;
            ret += (20.0 * Math.Sin(y * pi) + 40.0 * Math.Sin(y / 3.0 * pi)) * 2.0 / 3.0;
            ret += (160.0 * Math.Sin(y / 12.0 * pi) + 320 * Math.Sin(y * pi / 30.0)) * 2.0 / 3.0;
            return ret;
        }

        static double transformLon(double x, double y)
        {
            double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.Sqrt(Math.Abs(x));
            ret += (20.0 * Math.Sin(6.0 * x * pi) + 20.0 * Math.Sin(2.0 * x * pi)) * 2.0 / 3.0;
            ret += (20.0 * Math.Sin(x * pi) + 40.0 * Math.Sin(x / 3.0 * pi)) * 2.0 / 3.0;
            ret += (150.0 * Math.Sin(x / 12.0 * pi) + 300.0 * Math.Sin(x / 30.0 * pi)) * 2.0 / 3.0;
            return ret;
        }
        #endregion
    }
}
